package com.bz.xtcx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.*;
import com.bz.xtcx.manager.enums.UserTypeEnum;
import com.bz.xtcx.manager.mapper.*;
import com.bz.xtcx.manager.persist.conditions.*;
import com.bz.xtcx.manager.persist.paging.PageResponse;
import com.bz.xtcx.manager.service.IIndexService;
import com.bz.xtcx.manager.utils.ConfUtil;
import com.bz.xtcx.manager.utils.KeyValueTransUtil;
import com.bz.xtcx.manager.utils.WzStrUtil;
import com.bz.xtcx.manager.vo.VoQuery;
import com.bz.xtcx.manager.vo.VoResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IndexService extends BaseService implements IIndexService {
    @Autowired
    private CmsCategoryMapper cmsCategoryMapper;

    @Autowired
    private CmsContentMapper cmsContentMapper;

    @Autowired
    private CmsExchangesMapper cmsExchangesMapper;

    @Autowired
    private CmsExchangesEnrollMapper cmsExchangesEnrollMapper;

    @Autowired
    private CmsMeetingMapper cmsMeetingMapper;

    @Autowired
    private CmsFileMapper cmsFileMapper;

    @Autowired
    private LibExpertMapper libExpertMapper;

    @Autowired
    private LibEnterpriseMapper libEnterpriseMapper;

    @Autowired
    private LibCollegeMapper libCollegeMapper;

    @Autowired
    private LibServiceMapper libServiceMapper;

    @Autowired
    private LibReqMapper libReqMapper;

    @Autowired
    private LibResMapper libResMapper;
    
    @Autowired
    private BusUserFormHisMapper busUserFormHisMapper;
    
    @Autowired
    private BusUserMapper busUserMapper;

    @Autowired
    private IndexVisiterMapper indexVisiterMapper;

    @Autowired
    private BusUserFormMapper busUserFormMapper;

    @Autowired
    private DataStatisticsMapper dataStatisticsMapper;

    @Autowired
    private ResCodeCreater resCodeCreater;

    @Override
    public CmsCategory getCategoryByCode(String code) throws XtcxException {
        CmsCategory parentCategory = cmsCategoryMapper.selectByCode(code);
        if (null == parentCategory) {
            throw new XtcxException("未发现该栏目");
        }
        return parentCategory;
    }

    @Override
    public PageResponse<CmsCategory> listCategoryByParentCode(CategoryCondition cc) throws XtcxException {
        // 查询总记录数
        int itemTotal = 0;
        if (null != cc.getTotal() && 0 < cc.getTotal()) {
            itemTotal = cc.getTotal();
        } else {
            itemTotal = cmsCategoryMapper.countByParentCode(cc.getCode());
        }
        // 查询结果列表
        List<CmsCategory> categoryList = cmsCategoryMapper.selectByParentCode(cc);
        // 组织返回结果
        PageResponse<CmsCategory> respCategoryList = new PageResponse<CmsCategory>();
        if(cc.getNeedPaging()){
            respCategoryList.setCurrPage(cc.getCurrPage());
            respCategoryList.setPageSize(cc.getPageSize());
        }
        respCategoryList.setTotal(itemTotal);
        if (null == categoryList) {
            respCategoryList.setRows(new ArrayList<CmsCategory>());
        } else {
            respCategoryList.setRows(categoryList);
        }
        return respCategoryList;
    }

    @Override
    public PageResponse<CmsContent> listArticleByParentCode(ContentCondition cc) throws XtcxException {
        // 查询总记录数
        int itemTotal = 0;
        if (null != cc.getTotal() && 0 < cc.getTotal()) {
            itemTotal = cc.getTotal();
        } else {
            itemTotal = cmsContentMapper.countByCategoryCode(cc);
        }
        // 查询结果列表
        List<CmsContent> articleList = cmsContentMapper.selectByCategoryCode(cc);
        // 组织返回结果
        PageResponse<CmsContent> respArticleList = new PageResponse<CmsContent>();
        if(cc.getNeedPaging()){
            respArticleList.setCurrPage(cc.getCurrPage());
            respArticleList.setPageSize(cc.getPageSize());
        }
        respArticleList.setTotal(itemTotal);
        if (null == articleList) {
            respArticleList.setRows(new ArrayList<CmsContent>());
        } else {
            // 整理文章列表
            if (cc.isLoadAll()) {
                List<CmsContent> respContentList = new ArrayList<CmsContent>();
                CmsContent respContentVo = null;
                List<CmsFile> fileList = null;
                CmsFile fVo = null;
                String currContentId = null;
                for (CmsContent tmpArticle : articleList) {
                    if (null == currContentId) {
                        currContentId = tmpArticle.getId();
                        respContentVo = tmpArticle.copy();
                        fileList = new ArrayList<CmsFile>();
                    }
                    if (!currContentId.equals(tmpArticle.getId())) {
                        if (null != respContentVo) {
                            respContentVo.setCmsFileList(fileList);
                            respContentList.add(respContentVo);
                        }
                        currContentId = tmpArticle.getId();
                        respContentVo = tmpArticle.copy();
                        fileList = new ArrayList<CmsFile>();
                    }
                    if (WzStrUtil.isNotBlank(tmpArticle.getFileId())) {
                        fVo = new CmsFile();
                        fVo.setId(tmpArticle.getFileId());
                        fVo.setFileName(tmpArticle.getFileName());
                        fVo.setSavePath(tmpArticle.getSavePath());
                        fVo.setReqRelUrl(tmpArticle.getReqRelUrl());
                        fileList.add(fVo);
                    }
                }
                if (null != respContentVo) {
                    respContentVo.setCmsFileList(fileList);
                    respContentList.add(respContentVo);
                }
                respArticleList.setRows(respContentList);
            } else {
                respArticleList.setRows(articleList);
            }
        }
        return respArticleList;
    }

    @Override
    public PageResponse<CmsContent> listArticlesByKeyStrOrRecommend(ContentCondition cc) throws XtcxException {
        // 查询总记录数
        int itemTotal = 0;
        if (null != cc.getTotal() && 0 < cc.getTotal()) {
            itemTotal = cc.getTotal();
        } else {
            itemTotal = cmsContentMapper.countByKeyStrOrRecommend(cc);
        }
        // 查询结果列表
        List<CmsContent> articleList = cmsContentMapper.selectByKeyStrOrRecommend(cc);
        // 组织返回结果
        PageResponse<CmsContent> respArticleList = new PageResponse<CmsContent>();
        if(cc.getNeedPaging()){
            respArticleList.setCurrPage(cc.getCurrPage());
            respArticleList.setPageSize(cc.getPageSize());
        }
        respArticleList.setTotal(itemTotal);
        if (null == articleList) {
            respArticleList.setRows(new ArrayList<CmsContent>());
        } else {
            // 整理文章列表
            if (cc.isLoadAll()) {
                List<CmsContent> respContentList = new ArrayList<CmsContent>();
                CmsContent respContentVo = null;
                List<CmsFile> fileList = null;
                CmsFile fVo = null;
                String currContentId = null;
                for (CmsContent tmpArticle : articleList) {
                    if (null == currContentId) {
                        currContentId = tmpArticle.getId();
                        respContentVo = tmpArticle.copy();
                        fileList = new ArrayList<CmsFile>();
                    }
                    if (!currContentId.equals(tmpArticle.getId())) {
                        if (null != respContentVo) {
                            respContentVo.setCmsFileList(fileList);
                            respContentList.add(respContentVo);
                        }
                        currContentId = tmpArticle.getId();
                        respContentVo = tmpArticle.copy();
                        fileList = new ArrayList<CmsFile>();
                    }
                    if (WzStrUtil.isNotBlank(tmpArticle.getFileId())) {
                        fVo = new CmsFile();
                        fVo.setId(tmpArticle.getFileId());
                        fVo.setFileName(tmpArticle.getFileName());
                        fVo.setSavePath(tmpArticle.getSavePath());
                        fVo.setReqRelUrl(tmpArticle.getReqRelUrl());
                        fileList.add(fVo);
                    }
                }
                if (null != respContentVo) {
                    respContentVo.setCmsFileList(fileList);
                    respContentList.add(respContentVo);
                }
                respArticleList.setRows(respContentList);
            } else {
                respArticleList.setRows(articleList);
            }
        }
        return respArticleList;
    }

    @Override
    public CmsContent findArticleById(String id) throws XtcxException {
        List<CmsContent> contentList = cmsContentMapper.selectByPrimaryKey(id);
        if (null == contentList || 0 == contentList.size()) {
            return null;
        } else {
            CmsContent respContentVo = contentList.get(0).copy();
            List<CmsFile> fileList = new ArrayList<CmsFile>();
            CmsFile fVo = null;
            for (CmsContent tmpContent : contentList) {
                if (!respContentVo.getId().equals(tmpContent.getId())) {
                    break;
                }
                if (WzStrUtil.isNotBlank(tmpContent.getFileId())) {
                    fVo = new CmsFile();
                    fVo.setId(tmpContent.getFileId());
                    fVo.setFileName(tmpContent.getFileName());
                    fVo.setSavePath(tmpContent.getSavePath());
                    fVo.setReqRelUrl(tmpContent.getReqRelUrl());
                    fileList.add(fVo);
                }
            }
            respContentVo.setCmsFileList(fileList);
            return respContentVo;
        }
    }

    @Override
    public int updArticleClicks(String id) throws XtcxException {
        return cmsContentMapper.updateClicks(id);
    }

    @Override
    public PageResponse<CmsExchanges> listExcanges(ExchangeCondition ec) throws XtcxException {
        // 查询总记录数
        int itemTotal = 0;
        if (null != ec.getTotal() && 0 < ec.getTotal()) {
            itemTotal = ec.getTotal();
        } else {
            itemTotal = cmsExchangesMapper.countByCondition(ec);
        }
        // 查询结果列表
        List<CmsExchanges> exList = cmsExchangesMapper.selectByCondition(ec);
        // 组织返回结果
        PageResponse<CmsExchanges> respExPage = new PageResponse<CmsExchanges>();
        if(ec.getNeedPaging()){
            respExPage.setCurrPage(ec.getCurrPage());
            respExPage.setPageSize(ec.getPageSize());
        }
        respExPage.setTotal(itemTotal);
        if (null == exList) {
            respExPage.setRows(new ArrayList<CmsExchanges>());
        } else {
            // 整理文章列表
            if (ec.isLoadAll()) {
                List<CmsExchanges> respExList = new ArrayList<CmsExchanges>();
                CmsExchanges respExVo = null;
                List<CmsFile> fileList = null;
                CmsFile fVo = null;
                String currExId = null;
                for (CmsExchanges tmpEx : exList) {
                    if (null == currExId) {
                        currExId = tmpEx.getId();
                        respExVo = tmpEx.copy();
                        fileList = new ArrayList<CmsFile>();
                    }
                    if (!currExId.equals(tmpEx.getId())) {
                        if (null != respExVo) {
                            respExVo.setCmsFileList(fileList);
                            respExList.add(respExVo);
                        }
                        currExId = tmpEx.getId();
                        respExVo = tmpEx.copy();
                        fileList = new ArrayList<CmsFile>();
                    }
                    if (WzStrUtil.isNotBlank(tmpEx.getFileId())) {
                        fVo = new CmsFile();
                        fVo.setId(tmpEx.getFileId());
                        fVo.setFileName(tmpEx.getFileName());
                        fVo.setSavePath(tmpEx.getSavePath());
                        fVo.setReqRelUrl(tmpEx.getReqRelUrl());
                        fileList.add(fVo);
                    }
                }
                if (null != respExVo) {
                    respExVo.setCmsFileList(fileList);
                    respExList.add(respExVo);
                }
                for (CmsExchanges iVo : respExList) {
                    iVo.setExStatus(getExStatus(iVo));
                }
                respExPage.setRows(respExList);
            } else {
                for (CmsExchanges iVo : exList) {
                    iVo.setExStatus(getExStatus(iVo));
                }
                respExPage.setRows(exList);
            }
        }
        return respExPage;
    }

    public String getExStatus(CmsExchanges ce)  {
        //日期判断数值大小
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        int nowDt = Integer.parseInt(sdf.format(System.currentTimeMillis()).toString());
        int getEnrollStart=Integer.parseInt(sdf.format(ce.getEnrollStart()).toString());
        int getEnrollEnd=Integer.parseInt(sdf.format(ce.getEnrollEnd()).toString());
        int getExStart=Integer.parseInt(sdf.format(ce.getExStart()).toString());
        int getExEnd=Integer.parseInt(sdf.format(ce.getExEnd()).toString());
        if (nowDt<getExStart && nowDt<getEnrollStart) {
            return "未开始";
        } else if (nowDt>=getEnrollStart && nowDt<=getEnrollEnd && nowDt<getExStart) {
            return "报名中";
        } else if (nowDt> getEnrollEnd && nowDt<getExStart) {
            return "即将开始";
        } else if (nowDt>= getExStart  && nowDt<=getEnrollEnd ) {
            return "进行中,可报名";
        } else if (nowDt>=getExStart && nowDt<=getExEnd) {
            return "进行中";
        } else if (nowDt>getExEnd) {
            return "已结束";
        }
        return "";
    }


    @Override
    public CmsExchanges findExchangeById(String id) throws XtcxException {
        User loginedUser = getUser();
        String loginedUserId = null;
        if (null != loginedUser) {
            loginedUserId = loginedUser.getUserId();
        }
        List<CmsExchanges> exList = cmsExchangesMapper.selectByPrimaryKey(id, loginedUserId);
        if (null == exList || 0 == exList.size()) {
            return null;
        } else {
            CmsExchanges respExVo = exList.get(0).copy();
            List<CmsFile> fileList = new ArrayList<CmsFile>();
            CmsFile fVo = null;
            for (CmsExchanges tmpEx : exList) {
                if (!respExVo.getId().equals(tmpEx.getId())) {
                    break;
                }
                if (WzStrUtil.isNotBlank(tmpEx.getFileId())) {
                    fVo = new CmsFile();
                    fVo.setId(tmpEx.getFileId());
                    fVo.setFileName(tmpEx.getFileName());
                    fVo.setSavePath(tmpEx.getSavePath());
                    fVo.setReqRelUrl(tmpEx.getReqRelUrl());
                    fileList.add(fVo);
                }
            }
            respExVo.setCmsFileList(fileList);
            return respExVo;
        }
    }

    @Override
    public VoResponse enrollExchange(CmsExchangesEnroll cee) throws XtcxException {
        VoResponse resp = new VoResponse();
        User loginedUser = getUser();
        if (null == loginedUser || WzStrUtil.isBlank(loginedUser.getUserId())) {
            resp.setFail(resp);
            resp.setMessage("您尚未登录或已登录超时，请重新登录");
            return resp;
        }
        ExchangeEnrollCondition findCond = new ExchangeEnrollCondition();
        findCond.setLoginUserId(loginedUser.getUserId());
        findCond.setExId(cee.getExchangesId());
        int enrolledCnt = cmsExchangesEnrollMapper.countByCondition(findCond);
        if (0 < enrolledCnt) {
            resp.setSuccess(resp);
            resp.setMessage("您已经报名过该活动");
            return resp;
        }
        cmsExchangesEnrollMapper.insertSelective(cee);
        resp.setSuccess(resp);
        resp.setMessage("您已报名成功，请等待后续通知");
        return resp;
    }

    @Override
    public PageResponse<LibExpert> listExperts(LibCondition cc) throws XtcxException {
        PageResponse<LibExpert> pageList = new PageResponse<LibExpert>();
        if(cc.getNeedPaging()) {
            Page<LibExpert> page = PageHelper.startPage(cc.getCurrPage(), cc.getPageSize());
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
//            PageHelper.orderBy(" l.update_time desc, l.name desc ");
            // delete by wangtao on 201901301600 for 门户资源列表倒序 end
            libExpertMapper.findByConditionApi(cc);
            PageInfo<LibExpert> pageinfo = new PageInfo<LibExpert>(page);
            if (null != pageinfo.getList() && 0 < pageinfo.getList().size()) {
                LibExpert tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(1);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < pageinfo.getList().size(); i++) {
                    tmpLe = pageinfo.getList().get(i);
                    tmpLe.setSex(WzStrUtil.defaultString(tmpLe.getSex() == null ? "-" : tmpLe.getSex().equals("0") ? "女" : "男"));
                    tmpLe.setEducation(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "学历", tmpLe.getEducation())));
                    tmpLe.setDegree(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "学位", tmpLe.getDegree())));
                    tmpLe.setResearchField(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "研究领域", tmpLe.getResearchField())));
                    tmpLe.setTitleLevel(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "职称级别", tmpLe.getTitleLevel())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setTotal((int) pageinfo.getTotal());
            pageList.setRows(pageinfo.getList());
            pageList.setCurrPage(cc.getCurrPage());
            pageList.setPageSize(cc.getPageSize());
        }else {
            List<LibExpert> rows =  libExpertMapper.findByConditionApi(cc);
            if (null != rows && 0 < rows.size()) {
                LibExpert tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(1);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < rows.size(); i++) {
                    tmpLe = rows.get(i);
                    tmpLe.setSex(WzStrUtil.defaultString(tmpLe.getSex() == null ? "-" : tmpLe.getSex().equals("0") ? "女" : "男"));
                    tmpLe.setEducation(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "学历", tmpLe.getEducation())));
                    tmpLe.setDegree(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "学位", tmpLe.getDegree())));
                    tmpLe.setResearchField(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "研究领域", tmpLe.getResearchField())));
                    tmpLe.setTitleLevel(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "职称级别", tmpLe.getTitleLevel())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setRows(rows);
            pageList.setTotal(rows.size());
        }
        return pageList;
    }
    
    /**
     * 
     * @param id
     * @param userId
     * @param type
     * @return -2 没有联系方式或禁止对接用户；-1 待通知；0 已通知；1：已接受；2：已拒绝； 3：已超时；4：通知失败；
     * @throws XtcxException
     */
    public int allowCommunicate(String id, String userId, int type) throws XtcxException {
        if (WzStrUtil.isBlank(userId)) {
            return -1;
        }
        User user = getUser();
        if (null == user) {
            return -1;
        }
        if (0 == user.getUserType() || 101 == user.getUserType() || 102 == user.getUserType() || 103 == user.getUserType()) {
            return -2;
        }
        CmsMeeting meet = cmsMeetingMapper.selectByFromerAndResId(userId, id);
        if(meet != null) {
            int result = -1;
            if(type == UserTypeEnum.Expert.key()) {
                result = this.allowCommunicateAboutExpert(id, userId);
            }else if(type == UserTypeEnum.Service.key()) {
                result = this.allowCommunicateAboutService(id, userId);
            }else if(type == UserTypeEnum.Results.key()) {
                result = this.allowCommunicateAboutHarvest(id, userId);
            }else if(type == UserTypeEnum.Requirement.key()) {
                result = this.allowCommunicateAboutRequirement(id, userId);
            }
            if(result == -2) {
                return result;
            }
            if (2 == meet.getCheckStatus() || 3 == meet.getCheckStatus()) {
                return -1;
            } else if (-1 == meet.getCheckStatus() || 0 == meet.getCheckStatus()) {
                return -2;
            }
            return meet.getCheckStatus();
        }
        return -1;
    }

    public boolean allowCommunicate(String id, int type) throws XtcxException{
        User user = this.getUser();
        if (0 == user.getUserType() || 101 == user.getUserType() || 102 == user.getUserType() || 103 == user.getUserType()) {
            return false;
        }
        int result = 0;
        if(user != null) {
            result = this.allowCommunicate(id, user.getUserId(), type);
            if(result == -1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public LibExpert findExpertById(String id) throws XtcxException {
        User user = this.getUser();
        String userId = null;
        if(user != null) {
            userId = user.getUserId();
        }
        int status = this.allowCommunicate(id, userId, 1);
        LibExpert expert = libExpertMapper.findById(id);
        if(expert != null) {
            BusUserForm form = busUserFormMapper.findByType(1);
            JSONObject confJsonObj = JSON.parseObject(form.getDetail());
            expert.setSex(WzStrUtil.defaultString(expert.getSex() == null ? "-" : expert.getSex().equals("0") ? "女" : "男"));
            expert.setEducation(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "学历", expert.getEducation())));
            expert.setDegree(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "学位", expert.getDegree())));
            expert.setResearchField(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "研究领域", expert.getResearchField())));
            expert.setTitleLevel(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "职称级别", expert.getTitleLevel())));
            expert.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(expert.getCountry())));
//            if (WzStrUtil.isNotBlank(expert.getResearchWinning())) {
//                JSONArray rwJsonArr = JSON.parseArray(expert.getResearchWinning());
//                JSONObject rwJsonRow = null;
//                StringBuilder tmpRowStr = new StringBuilder("");
//                for (int i = 0; i < rwJsonArr.size(); i++) {
//                    rwJsonRow = rwJsonArr.getJSONObject(i);
//                    tmpRowStr.append("项目课题名:" + WzStrUtil.defaultString(rwJsonRow.getString("projectname"))).append("|");
//                    tmpRowStr.append("项目课题来源:" + WzStrUtil.defaultString(rwJsonRow.getString("projectSrc"))).append("|");
//                    tmpRowStr.append("完成情况:" + WzStrUtil.defaultString(rwJsonRow.getString("finishcon"))).append("|");
//                    tmpRowStr.append("完成时间:" + WzStrUtil.defaultString(rwJsonRow.getString("finishtime"))).append("|");
//                    tmpRowStr.append("奖项名称:" + WzStrUtil.defaultString(rwJsonRow.getString("rewname"))).append("|");
//                    tmpRowStr.append("获奖等级:" + WzStrUtil.defaultString(rwJsonRow.getString("rewlevel"))).append("|");
//                    tmpRowStr.append("获奖时间:" + WzStrUtil.defaultString(rwJsonRow.getString("rewtime"))).append("|");
//                    tmpRowStr.append("<br>");
//                }
//                expert.setResearchWinning(tmpRowStr.toString());
//            }

            expert.setNumber(WzStrUtil.defaultString(expert.getNumber()));
            expert.setName(WzStrUtil.defaultString(expert.getName()));//专家姓名
            expert.setBirthday(WzStrUtil.defaultString(expert.getBirthday()));
            expert.setSchool(WzStrUtil.defaultString(expert.getSchool()));
            expert.setCellphone(WzStrUtil.defaultString(expert.getCellphone()));//手机号
            expert.setTelephone(WzStrUtil.defaultString(expert.getTelephone()));
            expert.setEmail(WzStrUtil.defaultString(expert.getEmail()));
            expert.setResearchFieldOther(WzStrUtil.defaultString(expert.getResearchFieldOther()));//研究领域
            expert.setResearchArea(WzStrUtil.defaultString(expert.getResearchArea()));//研究方向
            expert.setAddress(WzStrUtil.defaultString(expert.getAddress()));//通讯地址
            expert.setWorkUnit(WzStrUtil.defaultString(expert.getWorkUnit()));//工作单位
            expert.setWorkDepartment(WzStrUtil.defaultString(expert.getWorkDepartment()));
            expert.setJobTitle(WzStrUtil.defaultString(expert.getJobTitle()));
            expert.setTitle(WzStrUtil.defaultString(expert.getTitle()));
            expert.setProjectDesc(WzStrUtil.defaultString(expert.getProjectDesc()));//主要产学研合作项目情况
            expert.setSuccessRecord(WzStrUtil.defaultString(expert.getSuccessRecord()));//主要学术成就/研究成果/管理成就
            expert.setResearchWinning(WzStrUtil.defaultString(expert.getResearchWinning()));

            // 用户说不显示内容 开始
//            expert.setNumber(null);
            expert.setBirthday("");
            expert.setSchool("");
            expert.setDegree("");
            expert.setEducation("");
            expert.setTitleLevel("");
            // 用户说不显示内容 结束
            expert.setCreater("");
            expert.setUpdater("");
            expert.setUserId("");
//            expert.setWorkUnit(null);
//            expert.setWorkDepartment(null);
            expert.setCode("");
            expert.setForm(null);
            expert.setFormId("");
            expert.setSearchParam("");
            if(status != 1) {//没有对接成功
                expert.setCellphone("");
//                expert.setCountry("");
                expert.setAddress("");
                expert.setTelephone("");
                expert.setEmail("");
            }
        }
        expert.setCheckStatus(String.valueOf(status));
        return expert;
    }

    @Override
    public int allowCommunicateAboutExpert(String id, String userId) throws XtcxException {
        if (WzStrUtil.isBlank(userId)) {
            return -1;
        }
        LibExpert lib = libExpertMapper.findById(id);
//        CmsMeeting cm = cmsMeetingMapper.selectByFromerAndResId(userId, id);
        if (null == lib || (!WzStrUtil.isMobile(lib.getCellphone()) && !WzStrUtil.isEmail(lib.getEmail()))) {
            return -2;
        }
        return -1;
//        return cm.getCheckStatus();

//        if(StringUtils.isEmpty(lib.getCellphone()) && StringUtils.isEmpty(lib.getEmail())) {
//            //资源库中联系信息为空；查找账号联系信息
////            BusUser user = null;
////            if(StringUtils.isEmpty(lib.getUserId())) {
////                user = busUserMapper.findByCode(lib.getCode());
////            }else {
////                user = busUserMapper.findById(lib.getUserId());
////            }
////            if(user == null) {
////                return -2; //没有联系方式
////            }
//            return -2;
//        }
//        return -1;//待通知
    }

    @Override
    public PageResponse<LibEnterprise> listEnterprises(LibCondition cc) throws XtcxException {
        PageResponse<LibEnterprise> pageList = new PageResponse<LibEnterprise>();
        if(cc.getNeedPaging()) {
            Page<LibEnterprise> page = PageHelper.startPage(cc.getCurrPage(), cc.getPageSize());
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
//            PageHelper.orderBy("l.name desc");
            // delete by wangtao on 201901301600 for 门户资源列表倒序 end
            libEnterpriseMapper.findByConditionApi(cc);
            PageInfo<LibEnterprise> pageinfo = new PageInfo<LibEnterprise>(page);
            if (null != pageinfo.getList() && 0 < pageinfo.getList().size()) {
                LibEnterprise tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(2);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < pageinfo.getList().size(); i++) {
                    tmpLe = pageinfo.getList().get(i);
                    tmpLe.setRegisteredCapital(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "企业规模", tmpLe.getRegisteredCapital())));
                    tmpLe.setRegisteredType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "注册类型", tmpLe.getRegisteredType())));
                    tmpLe.setIsHighNewTech(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "是否高新", tmpLe.getIsHighNewTech())));
                    tmpLe.setLocationNature(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "企业所在地性质", tmpLe.getLocationNature())));
                    tmpLe.setHighTechZone(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所在国家高新区", tmpLe.getHighTechZone())));
                    tmpLe.setIsListed(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "是否上市", tmpLe.getIsListed())));
                    tmpLe.setListedPlace(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "上市地点", tmpLe.getListedPlace())));
                    tmpLe.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", tmpLe.getDomain())));
                    tmpLe.setHighTitleType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "高层次人才类型", tmpLe.getHighTitleType())));
                    tmpLe.setPlatform(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "平台建设情况", tmpLe.getPlatform())));
                    tmpLe.setIsResearchWeapon(WzStrUtil.defaultString("1".equals(tmpLe.getIsResearchWeapon()) ? "是" : "否"));
                    tmpLe.setWeaponThreeEvidence(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "三证已获得", tmpLe.getWeaponThreeEvidence())));
                    tmpLe.setPlanApply(WzStrUtil.defaultString("1".equals(tmpLe.getPlanApply()) ? "是" : "否"));
                    tmpLe.setManagement(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "军民融合建设管理情况", tmpLe.getManagement())));
                    tmpLe.setJmrhDifficulty(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "民参军过程中遇到的障碍及困难", tmpLe.getJmrhDifficulty())));
                    tmpLe.setJmrhProblem(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "民参军过程中企业自身存在的问题", tmpLe.getJmrhProblem())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setTotal((int) pageinfo.getTotal());
            pageList.setRows(pageinfo.getList());
            pageList.setCurrPage(cc.getCurrPage());
            pageList.setPageSize(cc.getPageSize());
        }else {
            List<LibEnterprise> rows =  libEnterpriseMapper.findByConditionApi(cc);
            if (null != rows && 0 < rows.size()) {
                LibEnterprise tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(2);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < rows.size(); i++) {
                    tmpLe = rows.get(i);
                    tmpLe.setRegisteredCapital(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "企业规模", tmpLe.getRegisteredCapital())));
                    tmpLe.setRegisteredType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "注册类型", tmpLe.getRegisteredType())));
                    tmpLe.setIsHighNewTech(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "是否高新", tmpLe.getIsHighNewTech())));
                    tmpLe.setLocationNature(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "企业所在地性质", tmpLe.getLocationNature())));
                    tmpLe.setHighTechZone(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所在国家高新区", tmpLe.getHighTechZone())));
                    tmpLe.setIsListed(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "是否上市", tmpLe.getIsListed())));
                    tmpLe.setListedPlace(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "上市地点", tmpLe.getListedPlace())));
                    tmpLe.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", tmpLe.getDomain())));
                    tmpLe.setHighTitleType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "高层次人才类型", tmpLe.getHighTitleType())));
                    tmpLe.setPlatform(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "平台建设情况", tmpLe.getPlatform())));
                    tmpLe.setIsResearchWeapon(WzStrUtil.defaultString("1".equals(tmpLe.getIsResearchWeapon()) ? "是" : "否"));
                    tmpLe.setWeaponThreeEvidence(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "三证已获得", tmpLe.getWeaponThreeEvidence())));
                    tmpLe.setPlanApply(WzStrUtil.defaultString("1".equals(tmpLe.getPlanApply()) ? "是" : "否"));
                    tmpLe.setManagement(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "军民融合建设管理情况", tmpLe.getManagement())));
                    tmpLe.setJmrhDifficulty(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "民参军过程中遇到的障碍及困难", tmpLe.getJmrhDifficulty())));
                    tmpLe.setJmrhProblem(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "民参军过程中企业自身存在的问题", tmpLe.getJmrhProblem())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setRows(rows);
            pageList.setTotal(rows.size());
        }
        return pageList;
    }

    @Override
    public LibEnterprise findEnterpriseById(String id) throws XtcxException {
        User user = this.getUser();
        String userId = null;
        if(user != null) {
            userId = user.getUserId();
        }
        int status = this.allowCommunicate(id, userId, 2);
        LibEnterprise e = libEnterpriseMapper.findById(id);
        if(e != null) {
            BusUserForm form = busUserFormMapper.findByType(2);
            JSONObject confJsonObj = JSON.parseObject(form.getDetail());
            e.setRegisteredCapital(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "企业规模", e.getRegisteredCapital())));
            e.setRegisteredType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "注册类型", e.getRegisteredType())));
            // modify by wangtao on 20190103 for 查看企业详细信息报KV解析异常错误 start
            e.setIsHighNewTech(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "是否高新", e.getIsHighNewTech())));
            e.setIsListed(WzStrUtil.defaultString(KeyValueTransUtil.transChOnly(confJsonObj, "是否上市", e.getIsListed())));
            // modify by wangtao on 20190103 for 查看企业详细信息报KV解析异常错误 end
            e.setListedPlace(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "上市地点", e.getListedPlace())));
            e.setLocationNature(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "企业所在地性质", e.getLocationNature())));
            e.setHighTechZone(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所在国家高新区", e.getHighTechZone())));
            e.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", e.getDomain())));
            e.setHighTitleType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "高层次人才类型", e.getHighTitleType())));
            e.setPlatform(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "平台建设情况", e.getPlatform())));
            e.setIsResearchWeapon(WzStrUtil.defaultString("1".equals(e.getIsResearchWeapon()) ? "是" : "否"));
            e.setWeaponThreeEvidence(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "三证已获得", e.getWeaponThreeEvidence())));
            e.setPlanApply(WzStrUtil.defaultString("1".equals(e.getPlanApply()) ? "是" : "否"));
            e.setManagement(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "军民融合建设管理情况", e.getManagement())));
            e.setJmrhDifficulty(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "民参军过程中遇到的障碍及困难", e.getJmrhDifficulty())));
            e.setJmrhProblem(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "民参军过程中企业自身存在的问题", e.getJmrhProblem())));
            e.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(e.getCountry())));
            if (WzStrUtil.isNotBlank(e.getProject())) {
                JSONArray prjJsonArr = JSON.parseArray(e.getProject());
                JSONObject prjJsonRow = null;
//                StringBuilder tmpRowStr = new StringBuilder("");
                for (int i = 0; i < prjJsonArr.size(); i++) {
                    prjJsonRow = prjJsonArr.getJSONObject(i);
//                    tmpRowStr.append("项目名:" + WzStrUtil.defaultString(prjJsonRow.getString("name"))).append("|");
//                    JSONArray tmpDateArr = prjJsonRow.getJSONArray("time");
//                    if (null == tmpDateArr || 0 >= tmpDateArr.size()) {
//                        tmpRowStr.append("时间起:未填写|");
//                        tmpRowStr.append("时间止:未填写|");
//                    } else if (1 == tmpDateArr.size()) {
//                        tmpRowStr.append("时间起:" + WzStrUtil.defaultString((String) tmpDateArr.get(0))).append("|");
//                        tmpRowStr.append("时间止:未填写|");
//                    } else {
//                        tmpRowStr.append("时间起:" + WzStrUtil.defaultString((String) tmpDateArr.get(0))).append("|");
//                        tmpRowStr.append("时间止:" + WzStrUtil.defaultString((String) tmpDateArr.get(1))).append("|");
//                    }
//                    tmpRowStr.append("项目来源:" + WzStrUtil.defaultString(prjJsonRow.getString("source"))).append("|");
                    String fwbm = KeyValueTransUtil.transCh(confJsonObj, "服务部门", prjJsonRow.getString("fwbm"));
                    prjJsonRow.put("fwbm",fwbm);
                    String zxqk = KeyValueTransUtil.transCh(confJsonObj, "执行情况", prjJsonRow.getString("zxqk"));
                    prjJsonRow.put("zxqk",zxqk);
//                    tmpRowStr.append("服务部门:" + WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "服务部门", prjJsonRow.getString("fwbm")))).append("|");
//                    tmpRowStr.append("服务部门（其他）:" + WzStrUtil.defaultString(prjJsonRow.getString("fwbmOther"))).append("|");
//                    tmpRowStr.append("执行情况:" + WzStrUtil.defaultString(ConfUtil.transCh(confJsonObj, "执行情况", prjJsonRow.getString("zxqk")))).append("|");
//                    tmpRowStr.append("<br>");
                }
                e.setProject(WzStrUtil.defaultString(prjJsonArr.toString()));
            }

            e.setNumber(WzStrUtil.defaultString(e.getNumber()));
            e.setName(WzStrUtil.defaultString(e.getName()));
            e.setRegisteredTime(WzStrUtil.defaultString(e.getRegisteredTime()));
            e.setAddress(WzStrUtil.defaultString(e.getAddress()));
            e.setZipCode(WzStrUtil.defaultString(e.getZipCode()));
            e.setLocationNatureOther(WzStrUtil.defaultString(e.getLocationNatureOther()));
            e.setHighTechZoneOther(WzStrUtil.defaultString(e.getHighTechZoneOther()));
            e.setStockCode(WzStrUtil.defaultString(e.getStockCode()));
            e.setListedPlaceOther(WzStrUtil.defaultString(e.getListedPlaceOther()));
            e.setDomainOther(WzStrUtil.defaultString(e.getDomainOther()));
            e.setProduct(WzStrUtil.defaultString(e.getProduct()));
            e.setDeveloperNumber(WzStrUtil.defaultString(e.getDeveloperNumber()));
            e.setUndergraduateNum(WzStrUtil.defaultString(e.getUndergraduateNum()));
            e.setSeniorNum(WzStrUtil.defaultString(e.getSeniorNum()));
            e.setHighTitleNum(WzStrUtil.defaultString(e.getHighTitleNum()));
            e.setHighTitleTypeOther(WzStrUtil.defaultString(e.getHighTitleTypeOther()));
            e.setPlatformOther(WzStrUtil.defaultString(e.getPlatformOther()));
            e.setSecrecyOneTime(WzStrUtil.defaultString(e.getSecrecyOneTime()));
            e.setSecrecyTwoTime(WzStrUtil.defaultString(e.getSecrecyTwoTime()));
            e.setSecrecyThreeTime(WzStrUtil.defaultString(e.getSecrecyThreeTime()));
            e.setProduceTime(WzStrUtil.defaultString(e.getProduceTime()));
            e.setSupplierTime(WzStrUtil.defaultString(e.getSupplierTime()));
            e.setManagementName(WzStrUtil.defaultString(e.getManagementName()));
            e.setManagementZw(WzStrUtil.defaultString(e.getManagementZw()));
            e.setManagementPhone(WzStrUtil.defaultString(e.getManagementPhone()));
            e.setJmrhDifficultyOther(WzStrUtil.defaultString(e.getJmrhDifficultyOther()));
            e.setJmrhTech(WzStrUtil.defaultString(e.getJmrhTech()));
            e.setSharedResources(WzStrUtil.defaultString(e.getSharedResources()));
            e.setJmrhSuggest(WzStrUtil.defaultString(e.getJmrhSuggest()));
            e.setProject(WzStrUtil.defaultString(e.getProject()));
            e.setLxname(WzStrUtil.defaultString(e.getLxname()));
            e.setLxzw(WzStrUtil.defaultString(e.getLxzw()));
            e.setLxphone(WzStrUtil.defaultString(e.getLxphone()));
            e.setLxemail(WzStrUtil.defaultString(e.getLxemail()));
            e.setLpname(WzStrUtil.defaultString(e.getLpname()));
            e.setLpzw(WzStrUtil.defaultString(e.getLpzw()));
            e.setLpphone(WzStrUtil.defaultString(e.getLpphone()));
            e.setLpemail(WzStrUtil.defaultString(e.getLpemail()));

            // 用户提出不可见内容 开始
//            e.setNumber(null);
            e.setLocationNature("");
            e.setLocationNatureOther("");
            e.setHighTechZone("");
            e.setHighTechZoneOther("");
            e.setInventionNum("");
            e.setNewDrugNum("");
            e.setIcNum("");
            e.setUtilityModelNum("");
            e.setDesignNum("");
            e.setNationalNum("");
            e.setSoftwareNum("");
            e.setOtherInventionNum("");
            e.setResearchAmount("");
            e.setRdAmountLast("");
            e.setRdAmountBefore("");
            e.setRdAmountPrevious("");
            e.setSharedResources("");
            e.setJmrhDifficulty("");
            e.setJmrhDifficultyOther("");
            e.setJmrhProblem("");
            e.setJmrhSuggest("");
            // 用户提出不可见内容 结束
            e.setCreater("");
            e.setUpdater("");
            e.setUserId("");
            e.setCode("");
            e.setForm(null);
            e.setFormId("");
            e.setSearchParam("");
            if (1 != status) {
                e.setLpphone("");
                e.setLpemail("");
                e.setLxphone("");
                e.setLxemail("");
            }
        }
        return e;
    }

    @Override
    public PageResponse<LibCollege> listColleges(LibCondition cc) throws XtcxException {
        PageResponse<LibCollege> pageList = new PageResponse<LibCollege>();
        if(cc.getNeedPaging()) {
            Page<LibCollege> page = PageHelper.startPage(cc.getCurrPage(), cc.getPageSize());
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
//            PageHelper.orderBy("l.name desc");
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
            libCollegeMapper.findByConditionApi(cc);
            PageInfo<LibCollege> pageinfo = new PageInfo<LibCollege>(page);
            if (null != pageinfo.getList() && 0 < pageinfo.getList().size()) {
                LibCollege tmpLe = null;
                for (int i = 0; i < pageinfo.getList().size(); i++) {
                    tmpLe = pageinfo.getList().get(i);
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setTotal((int) pageinfo.getTotal());
            pageList.setRows(pageinfo.getList());
            pageList.setCurrPage(cc.getCurrPage());
            pageList.setPageSize(cc.getPageSize());
        }else {
            List<LibCollege> rows =  libCollegeMapper.findByConditionApi(cc);
            if (null != rows && 0 < rows.size()) {
                LibCollege tmpLe = null;
                for (int i = 0; i < rows.size(); i++) {
                    tmpLe = rows.get(i);
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setRows(rows);
            pageList.setTotal(rows.size());
        }
        return pageList;
    }

    @Override
    public LibCollege findCollegeById(String id) throws XtcxException {
        User user = this.getUser();
        String userId = null;
        if(user != null) {
            userId = user.getUserId();
        }
        int status = this.allowCommunicate(id, userId, 4);
        LibCollege e = libCollegeMapper.findById(id);
        if(e != null) {
            e.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(e.getCountry())));

            e.setNumber(WzStrUtil.defaultString(e.getNumber()));
            e.setName(WzStrUtil.defaultString(e.getName()));
            e.setAddress(WzStrUtil.defaultString(e.getAddress()));
            e.setZipCode(WzStrUtil.defaultString(e.getZipCode()));
            e.setUnitUrl(WzStrUtil.defaultString(e.getUnitUrl()));
            e.setMajorPlatform(WzStrUtil.defaultString(e.getMajorPlatform()));
            e.setIntroduction(WzStrUtil.defaultString(e.getIntroduction()));
            e.setLxName(WzStrUtil.defaultString(e.getLxName()));
            e.setLxMobile(WzStrUtil.defaultString(e.getLxMobile()));
            e.setLxEmail(WzStrUtil.defaultString(e.getLxEmail()));

            // 用户提出不可见内容 开始
//            e.setNumber(null);
            // 用户提出不可见内容 结束
            e.setCreater("");
            e.setUpdater("");
            e.setUserId("");
            e.setCode("");
            e.setForm(null);
            e.setFormId("");
            e.setSearchParam("");
            if(status != 1) {//没有对接成功
                e.setLxMobile("");
                e.setLxEmail("");
            }
        }
        return e;
    }

    @Override
    public PageResponse<LibServices> listServices(LibCondition cc) throws XtcxException {
        PageResponse<LibServices> pageList = new PageResponse<LibServices>();
        if(cc.getNeedPaging()) {
            Page<LibServices> page = PageHelper.startPage(cc.getCurrPage(), cc.getPageSize());
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
//            PageHelper.orderBy("l.name desc");
            // delete by wangtao on 201901301600 for 门户资源列表倒序 end
            libServiceMapper.findByConditionApi(cc);
            PageInfo<LibServices> pageinfo = new PageInfo<LibServices>(page);
            if (null != pageinfo.getList() && 0 < pageinfo.getList().size()) {
                LibServices tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(3);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < pageinfo.getList().size(); i++) {
                    tmpLe = pageinfo.getList().get(i);
                    tmpLe.setOrgNature(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "机构性质", tmpLe.getOrgNature())));
                    tmpLe.setOrgType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "机构类别", tmpLe.getOrgType())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setTotal((int) pageinfo.getTotal());
            pageList.setRows(pageinfo.getList());
            pageList.setCurrPage(cc.getCurrPage());
            pageList.setPageSize(cc.getPageSize());
        }else {
            List<LibServices> rows =  libServiceMapper.findByConditionApi(cc);
            if (null != rows && 0 < rows.size()) {
                LibServices tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(3);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < rows.size(); i++) {
                    tmpLe = rows.get(i);
                    tmpLe.setOrgNature(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "机构性质", tmpLe.getOrgNature())));
                    tmpLe.setOrgType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "机构类别", tmpLe.getOrgType())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setRows(rows);
            pageList.setTotal(rows.size());
        }
        return pageList;
    }

    @Override
    public LibServices findServiceById(String id) throws XtcxException {
        User user = this.getUser();
        String userId = null;
        if(user != null) {
            userId = user.getUserId();
        }
        int status = this.allowCommunicate(id, userId, 3);
        LibServices e = libServiceMapper.findById(id);
        if(e != null) {
            BusUserForm form = busUserFormMapper.findByType(3);
            JSONObject confJsonObj = JSON.parseObject(form.getDetail());
            e.setOrgNature(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "机构性质", e.getOrgNature())));
            e.setOrgType(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "机构类别", e.getOrgType())));
            e.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(e.getCountry())));
//            if (WzStrUtil.isNotBlank(e.getProject())) {
//                JSONArray prjJsonArr = JSON.parseArray(e.getProject());
//                JSONObject prjJsonRow = null;
//                StringBuilder tmpRowStr = new StringBuilder("");
//                for (int i = 0; i < prjJsonArr.size(); i++) {
//                    prjJsonRow = prjJsonArr.getJSONObject(i);
//                    tmpRowStr.append("项目名:" + WzStrUtil.defaultString(prjJsonRow.getString("name"))).append("|");
//                    JSONArray tmpDateArr = prjJsonRow.getJSONArray("time");
//                    if (null == tmpDateArr || 0 >= tmpDateArr.size()) {
//                        tmpRowStr.append("时间起:未填写|");
//                        tmpRowStr.append("时间止:未填写|");
//                    } else if (1 == tmpDateArr.size()) {
//                        tmpRowStr.append("时间起:" + WzStrUtil.defaultString((String) tmpDateArr.get(0))).append("|");
//                        tmpRowStr.append("时间止:未填写|");
//                    } else {
//                        tmpRowStr.append("时间起:" + WzStrUtil.defaultString((String) tmpDateArr.get(0))).append("|");
//                        tmpRowStr.append("时间止:" + WzStrUtil.defaultString((String) tmpDateArr.get(1))).append("|");
//                    }
//                    tmpRowStr.append("项目来源:" + WzStrUtil.defaultString(prjJsonRow.getString("source"))).append("|");
//                    tmpRowStr.append("资助方式:" + WzStrUtil.defaultString(ConfUtil.transCh(jsonObj, "资助方式", prjJsonRow.getString("registerSupport")))).append("|");
//                    tmpRowStr.append("资助方式（其他）:" + WzStrUtil.defaultString(prjJsonRow.getString("mechregisterSupportOther"))).append("|");
//                    tmpRowStr.append("执行情况:" + WzStrUtil.defaultString(ConfUtil.transCh(jsonObj, "执行情况", prjJsonRow.getString("registerImplement")))).append("|");
//                    tmpRowStr.append("<br>");
//                }
//                e.setProject(WzStrUtil.defaultString(tmpRowStr.toString()));
//            }
//            if (WzStrUtil.isNotBlank(e.getHonor())) {
//                JSONArray hoJsonArr = JSON.parseArray(e.getHonor());
//                JSONObject hoJsonRow = null;
//                StringBuilder tmpRowStr = new StringBuilder("");
//                for (int i = 0; i < hoJsonArr.size(); i++) {
//                    hoJsonRow = hoJsonArr.getJSONObject(i);
//                    tmpRowStr.append("荣誉名：" + WzStrUtil.defaultString(hoJsonRow.getString("name"))).append("；");
//                    tmpRowStr.append("获得时间：" + WzStrUtil.defaultString(hoJsonRow.getString("time"))).append("；");
//                    tmpRowStr.append("颁发机构：" + WzStrUtil.defaultString(hoJsonRow.getString("issuingAgency"))).append("；");
//                    tmpRowStr.append("<br>");
//                }
//                e.setHonor(WzStrUtil.defaultString(tmpRowStr.toString()));
//            }
//            if (WzStrUtil.isNotBlank(e.getWorkResult())) {
//                JSONArray wrJsonArr = JSON.parseArray(e.getWorkResult());
//                JSONObject wrJsonRow = null;
//                StringBuilder tmpRowStr = new StringBuilder("");
//                for (int i = 0; i < wrJsonArr.size(); i++) {
//                    wrJsonRow = wrJsonArr.getJSONObject(i);
//                    tmpRowStr.append("服务项目名:" + WzStrUtil.defaultString(wrJsonRow.getString("name"))).append("|");
//                    tmpRowStr.append("服务对象:" + WzStrUtil.defaultString(wrJsonRow.getString("object"))).append("|");
//                    JSONArray tmpDateArr = wrJsonRow.getJSONArray("time");
//                    if (null == tmpDateArr || 0 >= tmpDateArr.size()) {
//                        tmpRowStr.append("服务时间起:未填写|");
//                        tmpRowStr.append("服务时间止:未填写|");
//                    } else if (1 == tmpDateArr.size()) {
//                        tmpRowStr.append("服务时间起:" + WzStrUtil.defaultString((String) tmpDateArr.get(0))).append("|");
//                        tmpRowStr.append("服务时间止:未填写|");
//                    } else {
//                        tmpRowStr.append("服务时间起:" + WzStrUtil.defaultString((String) tmpDateArr.get(0))).append("|");
//                        tmpRowStr.append("服务时间止:" + WzStrUtil.defaultString((String) tmpDateArr.get(1))).append("|");
//                    }
//                    tmpRowStr.append("<br>");
//                }
//                e.setWorkResult(WzStrUtil.defaultString(tmpRowStr.toString()));
//            }

            e.setNumber(WzStrUtil.defaultString(e.getNumber()));
            e.setName(WzStrUtil.defaultString(e.getName()));
            e.setAddress(WzStrUtil.defaultString(e.getAddress()));
            e.setZipCode(WzStrUtil.defaultString(e.getZipCode()));
            e.setOrgNatureOther(WzStrUtil.defaultString(e.getOrgNatureOther()));
            e.setOrgTypeOther(WzStrUtil.defaultString(e.getOrgTypeOther()));
            e.setServicesProvided(WzStrUtil.defaultString(e.getServicesProvided()));
            e.setLpname(WzStrUtil.defaultString(e.getLpname()));
            e.setLpphone(WzStrUtil.defaultString(e.getLpphone()));
            e.setLpmobile(WzStrUtil.defaultString(e.getLpmobile()));
            e.setLpemail(WzStrUtil.defaultString(e.getLpemail()));
            e.setLinkman(WzStrUtil.defaultString(e.getLinkman()));
            e.setLxzw(WzStrUtil.defaultString(e.getLxzw()));
            e.setLxphone(WzStrUtil.defaultString(e.getLxphone()));
            e.setLxmobile(WzStrUtil.defaultString(e.getLxmobile()));
            e.setLxemail(WzStrUtil.defaultString(e.getLxemail()));
            e.setPersonnelNumber(WzStrUtil.defaultString(e.getPersonnelNumber()));
            e.setUndergraduateNumber(WzStrUtil.defaultString(e.getUndergraduateNumber()));
            e.setMiddleTitleNumber(WzStrUtil.defaultString(e.getMiddleTitleNumber()));
            e.setProject(WzStrUtil.defaultString(e.getProject()));
            e.setHonor(WzStrUtil.defaultString(e.getHonor()));
            e.setWorkResult(WzStrUtil.defaultString(e.getWorkResult()));

            // 用户提出不显示内容 开始
//            e.setNumber(null);
            e.setServiceAmountLast("");
            e.setServiceAmountBefore("");
            e.setServiceAmountPrevious("");
            e.setServiceQuantityLast("");
            e.setServiceQuantityBefore("");
            e.setServiceAmountPrevious("");
            // 用户提出不显示内容 结束
            e.setCreater("");
            e.setUpdater("");
            e.setUserId("");
            e.setCode("");
            e.setForm(null);
            e.setFormId("");
            e.setSearchParam("");
            if(status != 1) {//没有对接成功
                e.setLpphone("");
                e.setLpmobile("");
                e.setLpemail("");
                e.setLxphone("");
                e.setLxmobile("");
                e.setLxemail("");
            }
        }
        e.setCheckStatus(String.valueOf(status));
        return e;
    }
    
    @Override
    public int allowCommunicateAboutService(String id, String userId) throws XtcxException {
        if (WzStrUtil.isBlank(userId)) {
            return -1;
        }
        LibServices lib = libServiceMapper.findById(id);
//        CmsMeeting cm = cmsMeetingMapper.selectByFromerAndResId(userId, id);
        if (null == lib || (!WzStrUtil.isMobile(lib.getLxphone()) && !WzStrUtil.isEmail(lib.getLxemail()))) {
            return -2;
        }
        return -1;
//        return cm.getCheckStatus();
//        LibServices lib = libServiceMapper.findById(id);
//        if(StringUtils.isEmpty(lib.getLxphone()) && StringUtils.isEmpty(lib.getLxemail())) {
//            //资源库中联系信息为空；查找账号联系信息
////            BusUser user = null;
////            if(StringUtils.isEmpty(lib.getUserId())) {
////                user = busUserMapper.findByCode(lib.getCode());
////            }else {
////                user = busUserMapper.findById(lib.getUserId());
////            }
////            if(user == null) {
////                return -2; //没有联系方式
////            }
//            return -2;
//        }
//        return -1;//待通知
    }

    @Override
    public PageResponse<LibRequirements> listRequirements(LibCondition cc) throws XtcxException {
        PageResponse<LibRequirements> pageList = new PageResponse<LibRequirements>();
        if(cc.getNeedPaging()) {
            Page<LibRequirements> page = PageHelper.startPage(cc.getCurrPage(), cc.getPageSize());
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
//            PageHelper.orderBy("l.req_name desc");
            // delete by wangtao on 201901301600 for 门户资源列表倒序 end
            libReqMapper.findByConditionApi(cc);
            PageInfo<LibRequirements> pageinfo = new PageInfo<LibRequirements>(page);
            if (null != pageinfo.getList() && 0 < pageinfo.getList().size()) {
                LibRequirements tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(7);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < pageinfo.getList().size(); i++) {
                    tmpLe = pageinfo.getList().get(i);
                    tmpLe.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", tmpLe.getDomain())));
                    tmpLe.setReqBack(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "需求背景", tmpLe.getReqBack())));
                    tmpLe.setReqGet(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "合作方式", tmpLe.getReqGet())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setTotal((int) pageinfo.getTotal());
            pageList.setRows(pageinfo.getList());
            pageList.setCurrPage(cc.getCurrPage());
            pageList.setPageSize(cc.getPageSize());
        }else {
            List<LibRequirements> rows =  libReqMapper.findByConditionApi(cc);
            if (null != rows && 0 < rows.size()) {
                LibRequirements tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(7);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < rows.size(); i++) {
                    tmpLe = rows.get(i);
                    tmpLe.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", tmpLe.getDomain())));
                    tmpLe.setReqBack(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "需求背景", tmpLe.getReqBack())));
                    tmpLe.setReqGet(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "合作方式", tmpLe.getReqGet())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setRows(rows);
            pageList.setTotal(rows.size());
        }
        return pageList;
    }

    @Override
    public LibRequirements findRequirementById(String id) throws XtcxException {
        User user = this.getUser();
        String userId = null;
        if(user != null) {
            userId = user.getUserId();
        }
        int status = this.allowCommunicate(id, userId, 7);
        LibRequirements e = libReqMapper.findById(id);
        if(e != null) {
            BusUserForm form = busUserFormMapper.findByType(7);
            JSONObject confJsonObj = JSON.parseObject(form.getDetail());
            e.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", e.getDomain())));
            e.setReqBack(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "需求背景", e.getReqBack())));
            e.setReqGet(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "合作方式", e.getReqGet())));
            e.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(e.getCountry())));

            e.setReqName(WzStrUtil.defaultString(e.getReqName()));
            e.setNumber(WzStrUtil.defaultString(e.getNumber()));
            e.setName(WzStrUtil.defaultString(e.getName()));
            e.setAddress(WzStrUtil.defaultString(e.getAddress()));
            e.setFzname(WzStrUtil.defaultString(e.getFzname()));
            e.setFzzw(WzStrUtil.defaultString(e.getFzzw()));
            e.setFzemail(WzStrUtil.defaultString(e.getFzemail()));
            e.setFzphone(WzStrUtil.defaultString(e.getFzphone()));
            e.setFzname2(WzStrUtil.defaultString(e.getFzname2()));
            e.setFzzw2(WzStrUtil.defaultString(e.getFzzw2()));
            e.setFzemail2(WzStrUtil.defaultString(e.getFzemail2()));
            e.setFzphone2(WzStrUtil.defaultString(e.getFzphone2()));
            e.setDomainOther(WzStrUtil.defaultString(e.getDomainOther()));
            e.setReqBackOther(WzStrUtil.defaultString(e.getReqBackOther()));
            e.setReqDesc(WzStrUtil.defaultString(e.getReqDesc()));
            e.setReqNew(WzStrUtil.defaultString(e.getReqNew()));
            e.setReqOther(WzStrUtil.defaultString(e.getReqOther()));

            // 用户提出不可见内容 开始
//            e.setNumber(null);
            // 用户提出不可见内容 结束
            e.setCreater("");
            e.setUpdater("");
            e.setUserId("");
            e.setCode("");
            e.setForm(null);
            e.setFormId("");
            e.setSearchParam("");
            if(status != 1) {//没有对接成功
                e.setFzphone("");
                e.setFzemail("");
                e.setFzphone2("");
                e.setFzemail2("");
//                e.setCountry("");
//                e.setAddress("");
            }
        }
        e.setCheckStatus(String.valueOf(status));
        return e;
    }

    @Override
    public int allowCommunicateAboutRequirement(String id, String userId) throws XtcxException {
        if (WzStrUtil.isBlank(userId)) {
            return -1;
        }
        LibRequirements lib = libReqMapper.findById(id);
        if (null == lib) {
            return -2;
        }
//        CmsMeeting cm = cmsMeetingMapper.selectByFromerAndResId(userId, id);
        boolean isFzOk = false;
        boolean isLxOk = false;
        if (WzStrUtil.isNotBlank(lib.getFzname()) && (WzStrUtil.isMobile(lib.getFzphone()) || WzStrUtil.isEmail(lib.getFzemail()))) {
            isFzOk = true;
        }
        if (WzStrUtil.isNotBlank(lib.getFzname2()) && (WzStrUtil.isMobile(lib.getFzphone2()) || WzStrUtil.isEmail(lib.getFzemail2()))) {
            isLxOk = true;
        }
        if ((!isFzOk && !isLxOk)) {
            return -2;
        }
        return -1;
//        return cm.getCheckStatus();
//        LibRequirements lib = libReqMapper.findById(id);
//        if(StringUtils.isEmpty(lib.getFzphone()) && StringUtils.isEmpty(lib.getFzemail())) {
////            BusUser user = null;
////            if(StringUtils.isEmpty(lib.getUserId())) {
////                user = busUserMapper.findByCode(lib.getCode());
////            }else {
////                user = busUserMapper.findById(lib.getUserId());
////            }
////            if(user == null) {
////                return -2; //没有联系方式
////            }
//            return -2;
//        }
//        return -1;//待通知
    }

    @Override
    public PageResponse<LibResults> listHarvests(LibCondition cc) throws XtcxException {
        PageResponse<LibResults> pageList = new PageResponse<LibResults>();
        if(cc.getNeedPaging()) {
            Page<LibResults> page = PageHelper.startPage(cc.getCurrPage(), cc.getPageSize());
            // delete by wangtao on 201901301600 for 门户资源列表倒序 start
//            PageHelper.orderBy("l.res_name desc");
            // delete by wangtao on 201901301600 for 门户资源列表倒序 end
            libResMapper.findByConditionApi(cc);
            PageInfo<LibResults> pageinfo = new PageInfo<LibResults>(page);
            if (null != pageinfo.getList() && 0 < pageinfo.getList().size()) {
                LibResults tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(6);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < pageinfo.getList().size(); i++) {
                    tmpLe = pageinfo.getList().get(i);
                    tmpLe.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", tmpLe.getDomain())));
                    tmpLe.setStage(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所处阶段", tmpLe.getStage())));
                    tmpLe.setCooperation(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "合作方式", tmpLe.getCooperation())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setTotal((int) pageinfo.getTotal());
            pageList.setRows(pageinfo.getList());
            pageList.setCurrPage(cc.getCurrPage());
            pageList.setPageSize(cc.getPageSize());
        }else {
            List<LibResults> rows =  libResMapper.findByConditionApi(cc);
            if (null != rows && 0 < rows.size()) {
                LibResults tmpLe = null;
                BusUserForm form = busUserFormMapper.findByType(6);
                JSONObject confJsonObj = JSON.parseObject(form.getDetail());
                for (int i = 0; i < rows.size(); i++) {
                    tmpLe = rows.get(i);
                    tmpLe.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", tmpLe.getDomain())));
                    tmpLe.setStage(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所处阶段", tmpLe.getStage())));
                    tmpLe.setCooperation(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "合作方式", tmpLe.getCooperation())));
                    tmpLe.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(tmpLe.getCountry())));
                }
            }
            pageList.setRows(rows);
            pageList.setTotal(rows.size());
        }
        return pageList;
    }

    @Override
    public LibResults findHarvestById(String id) throws XtcxException {
        User user = this.getUser();
        String userId = null;
        if(user != null) {
            userId = user.getUserId();
        }
        int status = this.allowCommunicate(id, userId, 6);
        LibResults e = libResMapper.findById(id);
        if(e != null) {
            BusUserForm form = busUserFormMapper.findByType(6);
            JSONObject confJsonObj = JSON.parseObject(form.getDetail());
            e.setDomain(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所属领域", e.getDomain())));
            e.setStage(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "所处阶段", e.getStage())));
            e.setCooperation(WzStrUtil.defaultString(KeyValueTransUtil.transCh(confJsonObj, "合作方式", e.getCooperation())));
            e.setCountry(WzStrUtil.defaultString(KeyValueTransUtil.getPcaa(e.getCountry())));

//            if (WzStrUtil.isNotBlank(e.getPatents())) {
//                JSONArray patJsonArr = JSON.parseArray(e.getPatents());
//                JSONObject patJsonRow = null;
//                StringBuilder tmpRowStr = new StringBuilder("");
//                for (int i = 0; i < patJsonArr.size(); i++) {
//                    patJsonRow = patJsonArr.getJSONObject(i);
//                    tmpRowStr.append("序号:" + (i + 1)).append("；");
//                    tmpRowStr.append("专利名:" + WzStrUtil.defaultString(patJsonRow.getString("projectname"))).append("|");
//                    tmpRowStr.append("专利类型:" + WzStrUtil.defaultString(patJsonRow.getString("projecType"))).append("|");
//                    tmpRowStr.append("专利号:" + WzStrUtil.defaultString(patJsonRow.getString("projectNum"))).append("|");
//                    tmpRowStr.append("专利人:" + WzStrUtil.defaultString(patJsonRow.getString("projectPer"))).append("|");
//                    tmpRowStr.append("有效期:" + WzStrUtil.defaultString(patJsonRow.getString("projectTime"))).append("|");
//                    tmpRowStr.append("\r\n");
//                }
//                e.setPatents(tmpRowStr.toString());
//            }

            e.setResName(WzStrUtil.defaultString(e.getResName()));
            e.setNumber(WzStrUtil.defaultString(e.getNumber()));
            e.setName(WzStrUtil.defaultString(e.getName()));
            e.setAddress(WzStrUtil.defaultString(e.getAddress()));
            e.setFzname(WzStrUtil.defaultString(e.getFzname()));
            e.setFzemail(WzStrUtil.defaultString(e.getFzemail()));
            e.setFzphone(WzStrUtil.defaultString(e.getFzphone()));
            e.setFzname2(WzStrUtil.defaultString(e.getFzname2()));
            e.setFzemail2(WzStrUtil.defaultString(e.getFzemail2()));
            e.setFzphone2(WzStrUtil.defaultString(e.getFzphone2()));
            e.setDomainOther(WzStrUtil.defaultString(e.getDomainOther()));
            e.setResDesc(WzStrUtil.defaultString(e.getResDesc()));
            e.setUseArea(WzStrUtil.defaultString(e.getUseArea()));
            e.setNewIdea(WzStrUtil.defaultString(e.getNewIdea()));
            e.setSqPatent(WzStrUtil.defaultString(e.getSqPatent()));
            e.setHavePatent(WzStrUtil.defaultString(e.getHavePatent()));
            e.setOtherPatent(WzStrUtil.defaultString(e.getOtherPatent()));
            e.setPatents(WzStrUtil.defaultString(e.getPatents()));

            // 用户提出不可见内容 开始
//            e.setNumber(null);
            // 用户提出不可见内容 结束
            e.setCreater("");
            e.setUpdater("");
            e.setUserId("");
            e.setCode("");
            e.setForm(null);
            e.setFormId("");
            e.setSearchParam("");
            if(status != 1) {//没有对接成功
                e.setFzphone("");
                e.setFzemail("");
                e.setFzphone2("");
                e.setFzemail2("");
//                e.setCountry("");
//                e.setAddress("");
            }
        }
        e.setCheckStatus(String.valueOf(status));
        return e;
    }

    @Override
    public int allowCommunicateAboutHarvest(String id, String userId) throws XtcxException {
        if (WzStrUtil.isBlank(userId)) {
            return -1;
        }
        LibResults lib = libResMapper.findById(id);
        if (null == lib) {
            return -2;
        }
//        CmsMeeting cm = cmsMeetingMapper.selectByFromerAndResId(userId, id);
        boolean isFzOk = false;
        boolean isLxOk = false;
        if (WzStrUtil.isNotBlank(lib.getFzname()) && (WzStrUtil.isMobile(lib.getFzphone()) || WzStrUtil.isEmail(lib.getFzemail()))) {
            isFzOk = true;
        }
        if (WzStrUtil.isNotBlank(lib.getFzname2()) && (WzStrUtil.isMobile(lib.getFzphone2()) || WzStrUtil.isEmail(lib.getFzemail2()))) {
            isLxOk = true;
        }
        if ((!isFzOk && !isLxOk)) {
            return -2;
        }
        return -1;
//        return cm.getCheckStatus();
//        LibResults lib = libResMapper.findById(id);
//        if(StringUtils.isEmpty(lib.getFzphone()) && StringUtils.isEmpty(lib.getFzemail())) {
////            BusUser user = null;
////            if(StringUtils.isEmpty(lib.getUserId())) {
////                user = busUserMapper.findByCode(lib.getCode());
////            }else {
////                user = busUserMapper.findById(lib.getUserId());
////            }
////            if(user == null) {
////                return -2; //没有联系方式
////            }
//            return -2;
//        }
//        return -1;//待通知
    }

    @Override
    public VoResponse submitMeetingRequest(CmsMeeting cm) throws XtcxException {
        VoResponse resp = new VoResponse();
        User loginedUser = getUser();
        if (null == loginedUser || WzStrUtil.isBlank(loginedUser.getUserId())) {
            resp.setFail(resp);
            resp.setMessage("您尚未登录或已登录超时，请重新登录");
            return resp;
        }
        // 查询即存对接信息
        MeetingCondition findCond = new MeetingCondition();
        if (WzStrUtil.isNotBlank(cm.getId())) {
            findCond.setId(cm.getId());
        } else {
            findCond.setFromer(loginedUser.getUserId());
            findCond.setTargeter(cm.getTargeter());
            findCond.setTypeId(cm.getTypeId());
            if (1 == cm.getTypeId() || 2 == cm.getTypeId()) {
                findCond.setApplicationContentId(cm.getApplicationContentId());
            }
        }
        List<CmsMeeting> meetingList = cmsMeetingMapper.selectByCondition(findCond);
        // 新增或更新对接信息
        CmsMeeting updVo = new CmsMeeting();
        if (null == meetingList || 0 == meetingList.size()) {
            // Code自动生成
            String djCode = resCodeCreater.makeResCode("DJ");
            updVo.setCode(djCode);
            updVo.setTypeId(cm.getTypeId());
            updVo.setFromer(cm.getFromer());
            updVo.setTargeter(cm.getTargeter());
            updVo.setApplicationContentId(cm.getApplicationContentId());
            updVo.setApplicationNote(cm.getApplicationNote());
            updVo.setSubmitTime(new Date());
            updVo.setCheckStatus(-1);
            updVo.setCheckTime(cm.getCheckTime());
            updVo.setCheckContent(cm.getCheckContent());
            updVo.setRefuseCount(0);
            updVo.setCreater(loginedUser.getUserId());
            updVo.setUpdater(loginedUser.getUserId());
            cmsMeetingMapper.insertSelective(updVo);
        } else if (1 == meetingList.size()) {
            if (2 <= meetingList.get(0).getRefuseCount()) {
                resp.setFail(resp);
                resp.setMessage("您已多次联系对方并被对方拒绝，请勿再次打扰");
                return resp;
            } else if (0 == meetingList.get(0).getCheckStatus()) {
                resp.setFail(resp);
                resp.setMessage("已成功通知对方，请耐心等待对方回复。若3天后仍未收到回复，请登录确认");
                return resp;
            } else if (1 == meetingList.get(0).getCheckStatus()) {
                resp.setFail(resp);
                resp.setMessage("对方已同意您的请求，可于详情查看并通过对方联系方式进行沟通");
                return resp;
            } else {
                updVo.setId(cm.getId());
                updVo.setCheckStatus(-1);
                updVo.setSubmitTime(new Date());
                updVo.setUpdater(loginedUser.getUserId());
                cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
            }
        } else {
            resp.setFail(resp);
            resp.setMessage("对接信息错误，请联系管理员");
            return resp;
        }
        // 上传文件
        if (null != cm.getCmsFileList() && 0 < cm.getCmsFileList().size()) {
            CmsFile fiVo = null;
            for (CmsFile cf : cm.getCmsFileList()) {
                fiVo = new CmsFile();
                fiVo.setOwnerType(2);
                fiVo.setOwnerId(updVo.getId());
                fiVo.setFileName(cf.getFileName());
                fiVo.setSavePath(cf.getSavePath());
                fiVo.setReqRelUrl(cf.getReqRelUrl());
                cmsFileMapper.insert(fiVo);
            }
        }
        resp.setSuccess(resp);
        resp.setMessage("您已成功提交对接申请，请耐心等待对方回复。若3天后仍未收到回复，请登录确认");
        return resp;
    }

    @Override
    public VoResponse replyMeetingRequest(CmsMeeting cm) throws XtcxException {
        // TODO: 回复逻辑
        VoResponse resp = new VoResponse();
        
        return null;
    }

    @Override
    public VoResponse recordIndexVisit(IndexVisiter iv) throws XtcxException {
        VoResponse resp = new VoResponse();
        indexVisiterMapper.insertSelective(iv);
        resp.setSuccess(resp);
        return resp;
    }

    @Override
    public VoResponse countIndexVisit(int countType, IndexVisiterCondition vc) throws XtcxException {
        VoResponse resp = new VoResponse();
        // 统计截止到目前的全部访问量
        if (0 == countType) {
            int cnt = indexVisiterMapper.countByCondition(vc);
            resp.setSuccess(resp);
            resp.setMessage("访问量为：" + cnt);
            resp.setData(cnt);
            return resp;
            // 统计每个IP截止到目前的访问量
        } else if (1 == countType) {
            List<IndexVisiter> ret = indexVisiterMapper.countWithIpByCondition(vc);
            if (null == ret || 0 == ret.size()) {
                resp.setFail(resp);
                resp.setMessage("未获得数据");
                return resp;
            } else {
                resp.setSuccess(resp);
                resp.setData(ret);
                return resp;
            }
            // 统计每天每个IP的访问量
        } else if (2 == countType) {
            List<IndexVisiter> ret = indexVisiterMapper.countWithIpAndDayByCondition(vc);
            if (null == ret || 0 == ret.size()) {
                resp.setFail(resp);
                resp.setMessage("未获得数据");
                return resp;
            } else {
                resp.setSuccess(resp);
                resp.setData(ret);
                return resp;
            }
        }
        resp.setFail(resp);
        resp.setMessage("请选择统计类别");
        return resp;
    }

    @Override
    public VoResponse countIndexVisitAndMeetingAndUser() throws XtcxException {
        Integer vCnt = indexVisiterMapper.countByCondition(new IndexVisiterCondition());
        Integer amCnt = dataStatisticsMapper.countAllMeeting();
        Integer asmCnt = dataStatisticsMapper.countAllSuccessMeeting();
        VoQuery vq = new VoQuery();
        vq.setStatus("1");
        Integer uCnt = busUserMapper.findCount(vq);
        Map<String, Integer> retVo = new HashMap<String, Integer>();
        retVo.put("visitCnt", (null == vCnt ? 0 : vCnt));
        retVo.put("meetingCnt", (null == amCnt ? 0 : amCnt));
        retVo.put("successMeetingCnt", (null == asmCnt ? 0 : asmCnt));
        retVo.put("userCnt", (null == uCnt ? 0 : uCnt));
        VoResponse voRes = new VoResponse();
        voRes.setData(retVo);
        return voRes;
    }

    @Override
    public VoResponse getUserByToken() throws XtcxException {
        VoResponse voRes = new VoResponse();
        User u = getUser();
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("未登录或登录已超时，请重新登录");
            return voRes;
        }
        User ru = new User();
        ru.setCheckStatus(u.getCheckStatus());
        ru.setUserType(u.getUserType());
        ru.setUserName(u.getUserName());
        ru.setToken(u.getToken());
        ru.setOrgType(u.getOrgType());
        ru.setCellphone(u.getCellphone());
        ru.setEmail(u.getEmail());
        ru.setName(u.getName());
        voRes.setData(ru);
        return voRes;
    }
}
